import React, { Component } from 'react';
import { Table, Input, Modal, Form, Icon, Button, message, Popconfirm, Checkbox, Row, Col } from 'antd';

import Http from '../../../utils/http';
import './Usermanager.css'
import DateChange from '../../../utils/Date';
import ChangeUser from './ChangeUser'
import {withRouter} from "react-router-dom";
import Highlighter from 'react-highlight-words';
import {connect} from "dva";

const FormItem = Form.Item;
const { Search } = Input;
const CheckboxGroup = Checkbox.Group;

class Usermanager extends Component{
    constructor(props){
        super(props)
        this.state={
            dataSource:[],
            total:'',
            visible: false,
            searchText: '',
            searchedColumn: '',
        }
        this.http = this.http.bind(this)
    }
    // 获取用户列表
    http=()=>{
        Http('/api/Admin/getUserList','get',{index:'1',page_size:'9999'})
        .then((res)=>{
            if(res.code === 200){
                res.data.map((item)=>{
                   item.create_time = DateChange(item.create_time)
                })
                this.setState({
                    dataSource: res.data,
                    total: res.data.length
                })
            }
            if(res.code === 501){
                // alert('请登陆！')
                this.props.history.push('/login')
            }
            if(res.code === 500){
                message.error(res.msg)
              }
        })
        .catch((err)=>{
            console.log(err)
        })
    }
    componentDidMount(){
        this.http()
    }
    showModal = () => {
        this.setState({
          visible: true,
        });
      }
    //   用户新增
    handleOk = (e) => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
              Http('/user/User/addUser','post',values)
              .then((res)=>{
                  if(res.code === 200){
                      message.success('用户新增成功！')
                      this.http()
                      this.props.form.resetFields()
                  }
                  if(res.code === 500){
                    message.error(res.msg)
                  }
              })
              .catch((err)=>{
                  console.log(err)
              })
              this.setState({
                visible: false,
              });
            }
        })
      }
      handleCancel = (e) => {
        this.setState({
          visible: false,
        });
      }
      // 删除
    deleteUser=(record)=>{
        Http('/user/User/deleteUser','post',{user_id:record.user_id})
              .then((res)=>{
                  if(res.code === 200){
                      message.success('用户删除成功！')
                      this.http()
                  }else{
                      message.error(res.msg)
                  }
              })
              .catch((err)=>{
                  console.log(err)
              })
    }
    getColumnSearchProps = dataIndex => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
          <div style={{ padding: 8 }}>
            <Input
              ref={node => {
                this.searchInput = node;
              }}
              placeholder={`请输入搜索内容`}
              value={selectedKeys[0]}
              onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
              onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
              style={{ width: 188, marginBottom: 8, display: 'block' }}
            />
            <Button
              type="primary"
              onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
              icon="search"
              size="small"
              style={{ width: 90, marginRight: 8 }}
            >
              搜索
            </Button>
            <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
              重置
            </Button>
          </div>
        ),
        filterIcon: filtered => (
          <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
        ),
        onFilter: (value, record) =>
        record[dataIndex]&&record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: visible => {
          if (visible) {
            setTimeout(() => this.searchInput.select());
          }
        },
        render: text =>
          this.state.searchedColumn === dataIndex ? (
            <Highlighter
              highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
              searchWords={[this.state.searchText]}
              autoEscape
              textToHighlight={text&&text.toString()}
            />
          ) : (
            text
          ),
      });
      handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        this.setState({
          searchText: selectedKeys[0],
          searchedColumn: dataIndex,
        });
      };
    
      handleReset = clearFilters => {
        clearFilters();
        this.setState({ searchText: '' });
      };
    render(){
        const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form
        const columns=[{
            title: '用户ID',
            dataIndex: 'user_id',
            key: 'user_id',
        },{
            title: '创建时间',
            dataIndex: 'create_time',
            key: 'create_time',
        },{
            title: '姓名',
            dataIndex: 'real_name',
            key: 'real_name',
            ...this.getColumnSearchProps('real_name'),
        },{
            title: '登录名',
            dataIndex: 'user_name',
            key: 'user_name',
            ...this.getColumnSearchProps('user_name'),
        },{
            title: '手机号',
            dataIndex: 'mobile',
            key: 'mobile',
            ...this.getColumnSearchProps('mobile'),
        },{
            title: '操作',
            width:'300px',
            align: 'center',
            render: (record)=>{
                return(
                    <div>
                    {/* <ChangeUser http={this.http} id={record.user_id} name={record.user_name}/> */}
                    {/* <Popconfirm placement="leftTop" title='确定删除？' onConfirm={()=>this.deleteUser(record)} okText="确定" cancelText="取消">
                            <Button type='danger' size='small'>删除</Button>
                    </Popconfirm> */}
                    <UserBindRole id={record.user_id}/>
                    </div>
                )
            }
        },]
        return(
            <div className='Usermanager userAll'>
                <div className='head'>
                    <p>用户列表</p>
                </div>
                <div className='addUser'>
                    {/* <Button type="primary" onClick={this.showModal}>新增用户</Button> */}
                    <Modal
                    title="新增"
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    okText='确认'
                    cancelText= '取消'
                    >
                        <Form layout="inline" onSubmit={this.handleSubmit}>
                            <FormItem
                            label='用户名称'
                            >
                            {getFieldDecorator('user_name', {
                                rules: [{ required: true, message: '请输入用户名!' }],
                            })(
                                <Input  />
                            )}
                            </FormItem>
                            <FormItem
                            label='用户密码'
                            >
                            {getFieldDecorator('password', {
                                rules: [{ required: true, message: '请输入用户密码!' }],
                            })(
                                <Input />
                            )}
                            </FormItem>
                        </Form>
                    </Modal>
                </div>
                
                <Table columns={columns} dataSource={this.state.dataSource} bordered
                pagination={{
                    total: this.state.total, //数据总数量
                    size: 'small',
                    showQuickJumper: true,
                    pageSize: 10,  //显示几条一页
                    defaultPageSize: 10, //默认显示几条一页
                    showSizeChanger: true,  //是否显示可以设置几条一页的选项
                    // style: {marginRight:'50px'},
                    showTotal: ()=>{  //设置显示一共几条数据
                      return `共有${this.state.total}数据`
                      }
                  }}
                />
            </div>
        )
    }
}
const Usermanagers = Form.create()(Usermanager)
export default withRouter(Usermanagers)


@connect(({ video }) => ({
    video,
}))
class UserBindRole extends Component{
    state = {
        visible: false,
        options:[],
        checkbox: []
    }
    showModal = () => {
        // 获取角色列表
        Http('/fcinformation/Role/roleList','get',{index:'1'})
        .then((res)=>{
            if(res.code === 200){
                let options = [],i=0;
                res.data.list.map((item)=>{
                    options[i] ={
                        label: item.role_name,
                        value: item.role_id
                    }
                    i++
                })
                this.setState({
                    options: options
                })
            }
            if(res.code === 500){
                message.error(res.msg)
              }
        })
        .catch((err)=>{
            console.log(err)
        })
        // 获取用户已有角色
        Http('/fcinformation/User/userRole','get',{user_id:this.props.id})
        .then((res)=>{
            if(res.code === 200){
                this.setState({
                    checkbox: res.data
                })
            }
            if(res.code === 500){
                message.error(res.msg)
              }
        })
        .catch((err)=>{
            console.log(err)
        })
        this.setState({
            visible: true,
        });
    }
    // 绑定确定
    handleOk = (e) => {
        let data = {
            user_id: this.props.id,
            role_ids: this.state.checkbox
        }
        Http('/fcinformation/User/userBindRole','post',data)
        .then((res)=>{
            if(res.code === 200){
                message.success('已成功绑定角色！')
                this.setState({
                    visible: false,
                });
            }else{
                message.error(res.msg)
            }
        })
        .catch((err)=>{
            console.log(err)
        })
    }
    handleCancel = (e) => {
        this.setState({
        visible: false,
        });
    }
    // checkbox 改变
    checkboxChange=(checkedValues)=>{
        this.setState({
            checkbox: checkedValues
        })
    }
    render(){

        return(
            <div style={{display:'inline-block'}}>

                <Button size='small' style={{marginLeft:'10px'}} onClick={this.showModal}>绑定角色</Button>
      
                <Modal
                title="绑定角色"
                visible={this.state.visible}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                okText='确认'
                cancelText= '取消'
                width='60%'
                >
                    <Checkbox.Group onChange={this.checkboxChange} value={this.state.checkbox}>
                    <Row>
                    {
                        this.state.options.map((item)=>{
                            return(
                                <Col key={item.value} style={{marginBottom:'15px'}} span={8}><Checkbox value={item.value}>{item.label}</Checkbox></Col>
                            )
                        })
                    }
                     </Row>
                    </Checkbox.Group>
                </Modal>
            </div>
        )
    }
}
